<?php
/**
 *
 *
 *
 */
abstract class Yz_Form_Renderer_Abstract
    extends Yz_Class
    implements Yz_Form_Renderer_Interface
{

    /**
     * @var Yz_Item_Interface
     */
    protected $values;

    /**
     *  @var Yz_Form_Interface
     */
    protected $form;



    /****************************
     *      Public methods      *
     ****************************/

    public function __construct(Yz_Form_Interface $form)
    {
        $this->form = $form;
    }


    /** Assign values which will be used for rendering
     *  @param Yz_Item_Interface $values
     *  @return this
     */
    final public function setValues(Yz_Item_Interface $values=null)
    {
        $this->values = $values;
        return $this;
    }

    public function render(Yz_Template_Interface $template)
    {
        $o = $this->openFormHTML($template);
        foreach ($this->form as $element)
            $o .= $this->renderElement($element, $template);
        $o .= $this->closeFormHTML($template);
        return $o;
    }


    /****************************
     *      Protected methods   *
     ****************************/

    protected function renderElement(Yz_Form_Element_Interface $element, Yz_Template_Interface $template)
    {
        $elName = $element->getName();
        $callback = "renderElement_".$elName;
        if ($this->values)
            $element->setValue($this->values[$elName]);
        if (method_exists($this, $callback))
            return $this->$callback($element, $template);
        return $this->renderElementDefault($element, $template);
    }

    protected function renderElementDefault(Yz_Form_Element_Interface $element, Yz_Template_Interface $template)
    {
        $elName = $template->translate( $element->getName() );
        $el = $element->render($template);
        $o = <<<html
{$elName}: {$el}<br/>\n
html;
        return $o;
    }


    protected function openFormHTML(Yz_Template_Interface $template)
    {
        $form = $this->form;
        $action = rawurlencode($form->action);
        $o = <<<html
            <form name="{$form->name}" method="{$form->method}" action="{$action}">\n
html;
        return $o;
    }

    protected function closeFormHTML(Yz_Template_Interface $template)
    {
        $o = <<<html
            </form>\n
html;
        return $o;
    }

}
